# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import forms
from django.shortcuts import render,render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.http import HttpRequest
# Create your views here.
from my_from.models import User


class UserForm(forms.Form):
    username = forms.CharField(label='用户名',max_length=100)
    password = forms.CharField(label='密码',widget=forms.PasswordInput())


def login(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            username = user_form.cleaned_data['username']
            password = user_form.cleaned_data['password']

            user = User.objects.filter(username=username,password=password)
            print user.first().id
            request.session['user_id'] = user.first().id
            request.session.set_expiry(50)
            if user:
                response = HttpResponseRedirect('/form/index/')
                response.set_cookie('username',username,50)
                return response
            else:
                return HttpResponseRedirect('/form/login')
    else:
        user_form = UserForm()
        c = {'user_form':user_form,}
        return render(request,'login2.html',c)
def index(request):
    user_id = request.session.get('user_id')
    username = ''
    if user_id:
        user = User.objects.get(id = user_id)
        print  user
        username = user.username
    else:
        return HttpResponseRedirect('/form/login/')
    return render(request,'index.html',{'username':username})
def logout(request):
    del request.session['user_id']
    response = HttpResponse('退出成功')
    response.delete_cookie('username')
    return response



